
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
/*
 *  A class that listens to the port number and accepts
 *  requests from a java client (Applet).
 */
public class NetworkHandler {
	private String host;
	private String port;
	private String robotname;
	private Socket connection_img;
	private Socket connection_xml;
    private PrintWriter out;
    private BufferedReader in;
    private BufferedImage IMG;
    private DataInputStream din;
    private DataOutputStream dout;
    
	public NetworkHandler(String host, String port, String robotname) throws UnknownHostException, IOException {
		this.host = host;
		this.port = port;
        try {
            this.connection_img = new Socket(host, Integer.valueOf(port));
            this.connection_xml = new Socket(host, Integer.valueOf(port));
            System.out.println("Connection to " + connection_img.getInetAddress().getHostName());
            out = new PrintWriter(this.connection_xml.getOutputStream());
            in = new BufferedReader(new InputStreamReader(this.connection_xml.getInputStream()));
            din = new DataInputStream(connection_img.getInputStream()); 
            dout = new DataOutputStream(connection_img.getOutputStream());
            out.flush();
            dout.flush();
            this.send("robotname:" + robotname + "\n");
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host:"+host);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: "+host);
            System.exit(1);
        }
        System.out.println("done!");
	}
	
	/*
	 * OutputStream used for images.
	 */
	public DataInputStream getDin() {
		return this.din;
	}
	
	/*
	 * InputStream used for images.
	 */
	public DataOutputStream getDout() {
		return this.dout;
	}
	
	/*
	 * Wait for the client to send us data.
     * NOTE: this class probably needs changing because
     * readline terminates a string when \n is encoountered.
	 */
	public String read() throws IOException {
        return in.readLine();
	}
	
	/*
	 * Send String formated message to client,
	 * flushes the outputstream immediatly after that.
	 */
	public void send(String resp) {
       try {
		this.getDout().writeBytes(resp);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	
	/*
	 *  Close (safely) streams and sockets. 
	 */
	public void close() throws IOException {
        out.close();
        dout.close();
        in.close();
        din.close();
        connection_xml.close();
        connection_img.close();
	}
}
